package com.iter.devbox.datastructure;

/**
 * 顺序存储结构的顺序栈
 * 
 * @author Jimly
 */
public class Sqstack {

	/**数组*/
	private Object[] elementData;
	
	/**默认数组容量*/
	private static final int DEFAULT_CAPACITY = 10;
	
	/**数组中元素个数*/
	private int elementCount;
	
	public Sqstack() {
	}
	
	/**清空栈*/
	public boolean clear() {
		elementData = null;
		elementCount = 0;
		return true;
	}
	
	/**栈是否为空*/
	public boolean isEmpty() {
		if (elementData == null || elementCount == 0) {
			return true;
		} 
		return false;
	}
	
	/**获取栈顶元素*/
	public Object peek() {
		return elementData[elementCount-1];
	}
	
	/**向栈顶压入元素*/
	public Object push(Object object) {
		if (elementCount >= DEFAULT_CAPACITY) {
			//栈已满
			throw new RuntimeException("栈已满");
		}
		if (null == elementData) {
			elementData = new Object[DEFAULT_CAPACITY];
		}
		elementData[elementCount] = object;
		elementCount ++;
		return object;
	}
	
	/**从栈顶弹出元素*/
	public Object pop() {
		if (elementCount <= 0) {
			//空栈
			throw new RuntimeException("空栈");
		}
		Object obj = elementData[elementCount-1];
		elementCount --;
		return obj;
	}
	
	/**当前栈内元素个数*/
	public int size () {
		return elementCount;
	}

	/**main方法测试*/
	public static void main(String[] args) {
		Sqstack sqstack = new Sqstack();
		System.out.println("初始化：" + sqstack);
		sqstack.push("1");
		sqstack.push("2");
		sqstack.push("3");
		sqstack.push("4");
		sqstack.push("5");
		System.out.println("栈元素个数：" + sqstack.size());
		System.out.println("获取栈顶元素：" + sqstack.peek());
		System.out.println("弹出栈顶元素：" + sqstack.pop());
		System.out.println("出栈一个后元素个数：" + sqstack.size());
		System.out.println("栈是否为空：" + sqstack.isEmpty());
		System.out.println("获取栈顶元素：" + sqstack.peek());
		System.out.println("栈清空：" + sqstack.clear());
	}
}